package com.itheima.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.constant.CommonConstant;
import com.itheima.dto.DeleteDTO;
import com.itheima.dto.ShoppingCartDTO;
import com.itheima.entity.Flavors;
import com.itheima.entity.ShoppingCart;
import com.itheima.mapper.FlavorsMapper;

import com.itheima.service.ShoppingService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 购物车模块业务层实现类
 * @author msi
 */
@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Resource
    private FlavorsMapper flavorsMapper;
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public ShoppingCart addDish(ShoppingCartDTO shoppingCartDTO, String userId) {
        String key = CommonConstant.CART_DISH + userId;
        //调用修改方法 里面会判断是否有购物车对象有就只修改数量进行返回
        List<ShoppingCart> shoppingCarts = (List<ShoppingCart>) redisTemplate.opsForValue().get(key);
        if (shoppingCarts != null) {
            ShoppingCart shoppingCartOld = updateShoppingCart(shoppingCartDTO, userId);
            if (shoppingCartOld != null) {
                return shoppingCartOld;
            }
        }

        //设置新增菜品的各种信息
        ShoppingCart shoppingCart = new ShoppingCart();
        Snowflake snowflake = IdUtil.getSnowflake();
        String id = snowflake.nextIdStr();
        shoppingCart.setId(id);
        shoppingCart.setUserId(userId);
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);
        shoppingCart.setCreateTime(new Date());

        if (shoppingCartDTO.getDishId() != null) {
            QueryWrapper<Flavors> qw = new QueryWrapper<>();
            qw.eq("dish_id", shoppingCart.getDishId());
            List<Flavors> flavors = flavorsMapper.selectList(qw);
            StringBuilder sb = new StringBuilder();
            for (Flavors flavor : flavors) {
                String value = flavor.getValue();
                sb.append(value);
            }
            shoppingCart.setDishFlavor(sb.toString());
        }
        shoppingCart.setNumber(1);

        if (shoppingCarts == null) {
            shoppingCarts = new ArrayList<>();
        }
        //将封装号的商品项加入到购物车列表中 存到redis
        shoppingCarts.add(shoppingCart);
        redisTemplate.opsForValue().set(key, shoppingCarts, 7, TimeUnit.DAYS);
        return shoppingCart;
    }

    @Override
    public List<ShoppingCart> getList(String userId) {
        String key = CommonConstant.CART_DISH + userId;
        return (List<ShoppingCart>) redisTemplate.opsForValue().get(key);
    }

    @Override
    public void clean(String userId) {
        String key = CommonConstant.CART_DISH + userId;
        redisTemplate.delete(key);
    }

    @Override
    public Integer delete(DeleteDTO deleteDTO, String userId) {
        String key = CommonConstant.CART_DISH + userId;
        List<ShoppingCart> shoppingCarts =
                (List<ShoppingCart>) redisTemplate.opsForValue().get(key);
        //此处因为需要边遍历边删除，所以不能用for系遍历 会报null异常;
        Iterator<ShoppingCart> it = shoppingCarts.listIterator();

        while (it.hasNext()) {
            ShoppingCart shoppingCart = it.next();
            if (deleteDTO.getDishId() != null) {
                if (deleteDTO.getDishId().equals(shoppingCart.getDishId())) {
                    if (shoppingCart.getNumber() > 1) {
                        shoppingCart.setNumber(shoppingCart.getNumber() - 1);
                        redisTemplate.opsForValue().set
                        (key, shoppingCarts, 7, TimeUnit.DAYS);
                        return shoppingCart.getNumber();
                    } else {
                        it.remove();
                        redisTemplate.opsForValue().set
                        (key, shoppingCarts, 7, TimeUnit.DAYS);
                    }
                }
            } else {
                if (deleteDTO.getSetmealId().equals(shoppingCart.getSetmealId())) {
                    if (shoppingCart.getNumber() > 1) {
                        shoppingCart.setNumber(shoppingCart.getNumber() - 1);
                        redisTemplate.opsForValue().set
                        (key, shoppingCarts, 7, TimeUnit.DAYS);
                        return shoppingCart.getNumber();
                    } else {
                        it.remove();
                        redisTemplate.opsForValue().set
                        (key, shoppingCarts, 7, TimeUnit.DAYS);
                    }
                }
            }
        }
        return null;
    }

    /**
     * 方法名写错 应该是update 这是修改方法
     *
     * @param shoppingCartDTO
     * @return
     */
    private ShoppingCart updateShoppingCart(ShoppingCartDTO shoppingCartDTO, String userId) {

        String key = CommonConstant.CART_DISH + userId;
        List<ShoppingCart> shoppingCarts = (List<ShoppingCart>) redisTemplate.opsForValue().get(key);

        if (shoppingCarts != null) {
            for (ShoppingCart shoppingCart : shoppingCarts) {
                if (shoppingCartDTO.getDishId() != null) {
                    if (shoppingCartDTO.getDishId().equals(shoppingCart.getDishId())) {
                        shoppingCart.setNumber(shoppingCart.getNumber() + 1);
                        redisTemplate.opsForValue().set(key, shoppingCarts, 7, TimeUnit.DAYS);
                        return shoppingCart;
                    }
                } else if (shoppingCartDTO.getSetmealId().equals(shoppingCart.getSetmealId())) {
                    shoppingCart.setNumber(shoppingCart.getNumber() + 1);
                    redisTemplate.opsForValue().set(key, shoppingCarts, 7, TimeUnit.DAYS);
                    return shoppingCart;
                }
            }
        }
        return null;
    }
}
